<template>
  <el-tabs v-model="activeName">
    <el-tab-pane label=" 图文管理
  " name="news">
      <div class="btn" style="margin-bottom: 10px">
        <el-button size="small" @click="SynchroMaterial(activeName)" type="primary">同步</el-button>
        <el-button size="small" @click="model('show','newsModel')" type="primary">添加新图文
        </el-button>
      </div>
      <div class="clearfix Waterfall" ref="Waterfall">
        <div class="news-container" v-for="(item , index) in materialListData['news'][currentPage]">
          <ul class="news-content" v-if="item.content.news.length > 1">
            <li>
              <div class="mainImg">
                <div class="img">
                  <img
                    :src="item.content.news[0].thumb_url ? 'http://localhost:3000/weChat/wximg?url='+item.content.news[0].thumb_url : item.content.news[0].url">
                </div>
                <div class="mainTitle">
                  {{item.content.news[0].title}}
                </div>
              </div>
            </li>
            <li class="clearfix" v-for="(i, n) in item.content.news" v-if="n > 0">
              <div class="viceTitle">
                <div>
                  {{item.content.news[n].title}}
                </div>
              </div>
              <div class="viceImg">
                <img
                  :src="item.content.news[0].thumb_url ? 'http://localhost:3000/weChat/wximg?url='+item.content.news[0].thumb_url : item.content.news[0].url">
              </div>
            </li>
          </ul>
          <ul class="news-content" v-else>
            <li>
              <div class="mainImg">
                <div class="img">
                  <img
                    :src="item.content.news[0].thumb_url ? 'http://localhost:3000/weChat/wximg?url='+item.content.news[0].thumb_url : item.content.news[0].url">
                </div>
                <div class="singleTitle">
                  {{item.content.news[0].title}}
                  <div class="digest">
                    {{item.content.news[0].digest || item.content.news[0].description}}
                  </div>
                </div>
              </div>
            </li>
          </ul>
          <div class="btns">
            <el-button size="mini" @click="delMaterial(item, $event)">删除</el-button>
            <el-button size="mini" @click="model('show','model',item.content.media_id)">群发</el-button>
            <el-button size="mini" @click="previewNews(item.content)">预览</el-button>
          </div>
        </div>
      </div>
      <div class="page">
        <el-pagination
          @current-change="handleCurrentChange"
          :page-size="20"
          :current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :total="currentTotalNumber">
        </el-pagination>
      </div>
    </el-tab-pane>
    <el-tab-pane label=" 图片管理
  " name="image">
      <div class="btn" style="margin-bottom: 10px">
        <el-button size="small" @click="SynchroMaterial(activeName)" type="primary">同步</el-button>
      </div>
      <div class="image">
        <ul class="clearfix">
          <li v-for="(item , index) in materialListData['image'][currentPage]">
            <div class="img">
              <img :src="'http://localhost:3000/weChat/wximg?url='+item.content.url"/>
            </div>
            <div class="btns">
              <el-button size="mini" @click="delMaterial(item, $event)">删除</el-button>
              <el-button size="mini" @click="model('show',item.content.media_id)">群发</el-button>
              <el-button size="mini" @click="previewNews(item.content)">预览</el-button>
            </div>
          </li>
        </ul>
      </div>
      <div class="page">
        <el-pagination
          @current-change="handleCurrentChange"
          :page-size="20"
          :current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :total="currentTotalNumber">
        </el-pagination>
      </div>
    </el-tab-pane>
    <!--分组模态框-->
    <div ref="model" class="model">
      <div>
        <div class="title">
          群发
        </div>
        <div style="color: #999;padding-left: 15px;font-size: 12px">
          请选择下拉中的组来进行群发！
        </div>
        <div class="content">
          <el-autocomplete
            popper-class="my-autocomplete"
            v-model="tagName"
            :fetch-suggestions="bindquerySearch"
            placeholder="请输入内容"
            style="width: 100%"
            @select="handleSelect">
            <i
              class="el-icon-edit el-input__icon"
              slot="suffix"
              @click="handleIconClick">
            </i>
            <template slot-scope="props">
              <div class="name">{{ props.item.name }}</div>
              <span class="addr">id : {{ props.item.id }}</span>
            </template>
          </el-autocomplete>
        </div>
        <div class="bottomBtn">
          <el-button @click="model('hide','model')" size="mini">取消</el-button>
          <el-button @click="MassMaterial()" type="primary" size="mini">确认</el-button>
        </div>
      </div>
    </div>
    <!--添加新图文模态框-->
    <div ref="newsModel" class="newsModel">
      <div class="title">
        添加新图文
      </div>
      <div class="news-content">
        <news-assembly></news-assembly>
      </div>
      <div class="bottomBtn">
        <el-button @click="model('hide','newsModel')" size="mini">取消</el-button>
        <el-button @click="MassMaterial()" type="primary" size="mini">确认</el-button>
      </div>
    </div>
    <div ref="bgMmodel" @click="model('hide')" class="bg-model"></div>
  </el-tabs>
</template>
<script type="text/ecmascript-6">
  import newsAssembly from '../../common/newsAssembly/newsAssembly.vue'

  export default {
    components: {newsAssembly},
    data() {
      return {
        activeName: 'news',
        currentPage: 1,   // 当前页数
        currentTotalNumber: 1,   // 当前类型总数
        TotalNumber: {
          'news': 0,
          'image': 10
        }, // 总数据条数
        clickPage: {
          'news': [1],
          'image': []
        }, // 避免重复获取数据
        materialListData: {
          'news': {},
          'image': {}
        },
        tagListData: [],  // 标签列表
        mediaId: '',
        tagId: '',
        tagName: ''
      }
    },
    mounted() {
      this.tagList()
    },
    methods: {
      // 当期点击的分页
      handleCurrentChange(val) {
        const _self = this
        if (_self.clickPage[_self.activeName].indexOf(val) === -1) {
          _self.clickPage[_self.activeName].push(val)
          _self.clickPage[_self.activeName].push(val)
          _self.newsMaterial(_self.activeName, val)
        } else {
          _self.currentPage = val
          if (_self.activeName === 'news') {
            setTimeout(function () {
              _self.Waterfall()
            }, 0)
          }
        }
      },
      // 瀑布流
      Waterfall() {
        let _self = this
        let Waterfall = _self.$refs.Waterfall
        let children = Waterfall.children
        let height = []
        let indexMin = 0
        let heightMin = 0
        for (let i = 0; i < children.length; i++) {
          if (i <= 3) {
            children[i].style.top = 0
            children[i].style.left = 390 * i + 'px'
            height.push(children[i].clientHeight)
          } else {
            heightMin = Math.min.apply(null, height)
            indexMin = height.indexOf(heightMin)
            children[i].style.top = height[indexMin] + 10 + 'px'
            children[i].style.left = 390 * indexMin + 'px'
            height[indexMin] = height[indexMin] + children[i].clientHeight + 10
          }
        }
        Waterfall.style.height = Math.max.apply(null, height) + 20 + 'px'
      },
      SynchroMaterial(type) {
        const _self = this
        this.$confirm('确认要同步吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _self.$ajax.post('/weChat/WXgetMaterial', {type: type}).then(function (response) {
            if (response.data.code === -1) {
              _self.$message({
                type: 'info',
                message: response.data.msg
              })
            } else {
              _self.newsMaterial(type, 1)
            }
          }).catch(function (error) {
            console.log(error)
          })
        }).catch(() => {
        })
      },
      newsMaterial(type, currentPage) {
        const _self = this
        _self.$ajax.post('/weChat/getMaterial', {currentPage: currentPage, type: type}).then(function (response) {
          if (response.data.data.currentPage === 1) {
            _self.TotalNumber[type] = response.data.data.TotalNumber
            _self.currentTotalNumber = _self.TotalNumber[type]
          }
          _self.materialListData[type][response.data.data.currentPage] = response.data.data.material
          _self.currentPage = response.data.data.currentPage
          if (type === 'news') {
            setTimeout(function () {
              _self.Waterfall()
            }, 0)
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      delMaterial(item, e) {
        const _self = this
        this.$confirm('确认要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _self.$ajax.post('/weChat/delMaterial', {
            media_id: item.content.media_id,
            id: item._id
          }).then(function (response) {
            if (response.data.code === -1) {
              _self.$message({
                type: 'info',
                message: response.data.msg
              })
            } else {
              _self.materialListData[_self.activeName][_self.currentPage].splice(_self.materialListData[_self.activeName][_self.currentPage].indexOf(item), 1)
              e.target.innerHTML === '删除' ? e.target.parentNode.parentNode.parentNode.remove() : e.target.parentNode.parentNode.remove()
              setTimeout(function () {
                _self.Waterfall()
              }, 0)
            }
          }).catch(function (error) {
            console.log(error)
          })
        }).catch(() => {
        })
      },
      previewNews(data) {
        const _self = this
        this.$prompt('请输入预览人的openid', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({value}) => {
          _self.$ajax.post('/weChat/previewNews', {
            mediaId: data.media_id || null,
            openid: value,
            type: _self.activeName,
            news: data.news
          }).then(function (response) {
            _self.$message({
              type: 'info',
              message: response.data.msg
            })
          }).catch(function (error) {
            console.log(error)
          })
        }).catch(() => {
        })
      },
      MassMaterial() {
        const _self = this
        if (_self.tagId === '') {
          _self.$message({
            type: 'info',
            message: '未选择分组'
          })
          return
        }
        _self.$ajax.post('/weChat/MassMaterial', {
          type: _self.activeName,
          mediaId: _self.mediaId,
          receivers: _self.tagId
        }).then(function (response) {
          _self.$message({
            type: 'info',
            message: response.data.msg
          })
        }).catch(function (error) {
          console.log(error)
        })
      },
      Callback() {
        // （绑定/取消绑定）禁用滚动条的回调函数
        // 写在这里的原因是：放在model方法里每次点击都会创建一个Callback方法 导致了取消绑定 和 绑定的Callback方法不是同一个
        if (document.body.scrollTop) {
          document.body.scrollTop = this.scrollTop
        } else {
          document.documentElement.scrollTop = this.scrollTop
        }
      },
      model(state, elm, mediaId) {
        const _self = this
        let bgMmodel = _self.$refs.bgMmodel
        // 让_self.Callback方法可以获取到scrollTop
        _self.scrollTop = document.body.scrollTop || document.documentElement.scrollTop

        function eventBind() {
          if (document.attachEvent) {
            document.attachEvent('onscroll', _self.Callback, false)
          } else {
            document.addEventListener('scroll', _self.Callback, false)
          }
        }

        function cancelEventBind() {
          if (document.detachEvent) {
            document.detachEvent('onscroll', _self.Callback, false)
          } else {
            document.removeEventListener('scroll', _self.Callback, false)
          }
        }

        if (elm === undefined) {
          _self.mediaId = ''
          bgMmodel.style.opacity = 0
          bgMmodel.style.visibility = 'hidden'
          _self.$refs.model.style.visibility = 'hidden'
          _self.$refs.model.style.opacity = 0
          _self.$refs.model.style.marginTop = '-20px'
          _self.$refs.newsModel.style.visibility = 'hidden'
          _self.$refs.newsModel.style.opacity = 0
          _self.$refs.newsModel.style.marginTop = '-20px'
          cancelEventBind()
          return
        }
        let model = _self.$refs[elm]
        if (state === 'show') {
          _self.mediaId = mediaId
          bgMmodel.style.opacity = 0.5
          bgMmodel.style.visibility = 'inherit'
          model.style.visibility = 'inherit'
          model.style.opacity = 1
          model.style.marginTop = '0'
          eventBind()
        } else {
          _self.mediaId = ''
          bgMmodel.style.opacity = 0
          bgMmodel.style.visibility = 'hidden'
          model.style.visibility = 'hidden'
          model.style.opacity = 0
          model.style.marginTop = '-20px'
          cancelEventBind()
        }
      },
      // 获取标签列表
      tagList() {
        let _self = this
        _self.$ajax.post('/weChat/tagList').then(function (response) {
          if (response.data.code === 0) {
            _self.tagListData = response.data.data
            _self.tagListData.unshift({name: '所有人', id: true})
          } else {
            _self.$message({
              type: 'info',
              message: '获取标签失败！'
            })
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      bindquerySearch(queryString, cb) {
        var restaurants = this.tagListData
        var results = queryString ? restaurants.filter(this.createFilter(queryString, 'name')) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      createFilter(queryString, key) {
        return (restaurant) => {
          return (restaurant[key].toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      handleSelect(item) {
        this.tagName = item.name
        this.tagId = item.id
      },
      handleIconClick(ev) {
        console.log(ev)
      }
      // 获取标签列表
      // 添加新图文模态框
    },
    watch: {
      activeName() {
        const _self = this
        _self.currentPage = 1
        _self.currentTotalNumber = _self.TotalNumber[_self.activeName]
        if (_self.activeName === 'news') {
          setTimeout(function () {
            _self.Waterfall()
          }, 0)
        }
        if (_self.clickPage[this.activeName].length <= 0) {
          this.newsMaterial(this.activeName, 1)
        }
      }
    },
    created() {
      this.newsMaterial(this.activeName, 1)
    }
  }
</script>
<style lang='less' scoped>
  @import "newsMaterial";
</style>
